package com.roy.spring.multitenant.controller;

import com.roy.spring.multitenant.tenant.TenantContext;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * Created by admin on 17-11-26.
 */
@Controller
public class SchemaController {

    @Autowired
    private DataSource dataSource;


    public String initSchema(@RequestHeader("X-TenantID") String tenantName)throws Exception {
        TenantContext.setTenant(tenantName);

        Connection conn = dataSource.getConnection();
        conn.createStatement().execute("create schema " + tenantName + "");
        SchemaUpdate schemaUpdate = new SchemaUpdate(null);

        schemaUpdate.execute(true, true);

        conn.createStatement().execute("set schema '" + tenantName + "'");

        return "ok";
    }


}

